<?php

// Code for Session Cookie workaround.
if (isset($_POST["PHPSESSID"])) {
  session_id($_POST["PHPSESSID"]);
}

session_start();

// Settings.
if (isset($_POST["UPLOAD_DIRECTORY"])) {
  $save_path = $_POST["UPLOAD_DIRECTORY"]; // The path were we will save the file (getcwd() may not be reliable and should be tested in your environment).
}
else {
  $save_path = "";
}

$upload_name = "Filedata";
if (isset($_POST["PACKAGE_NAME"])) {
  $package_name = $_POST["PACKAGE_NAME"];
}
else {
  $package_name = "";
}
$valid_chars_regex = '.A-Z0-9_ !@#$%^&()+={}\[\]\',~`-'; // Characters allowed in the file name (in a Regular Expression format).

$file_name = preg_replace('/[^'.$valid_chars_regex.']|\.+$/i', "", basename($_FILES[$upload_name]['name']));

// Validate file extension.
if (@strpos($_FILES[$upload_name]['name'], $package_name) !== false && strpos($_FILES[$upload_name]['name'], $package_name) == '0') {
}
else {
  HandleError("Invalid file extension");
  exit(0);
}

// If file already exists, then delete it before moving the new one.
if (file_exists($save_path . '/' . $file_name)) {
  @unlink($save_path . '/' . $file_name);
}

// Process the file.
if (!move_uploaded_file($_FILES[$upload_name]["tmp_name"], $save_path . '/' . $file_name)) {
  HandleError("File could not be saved: " . $save_path . '/' . $file_name);
  exit(0);
}

// Return output to the browser (only supported by SWFUpload for Flash Player 9).
echo "File Received";
exit(0);


/* Handles the error output.  This function was written for SWFUpload for Flash Player 8 which
cannot return data to the server, so it just returns a 500 error. For Flash Player 9 you will
want to change this to return the server data you want to indicate an error and then use SWFUpload's
uploadSuccess to check the server_data for your error indicator. */
function HandleError($message) {
  echo $message;
}
?>